package com.vipshop.util;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

public class FileHelper {

	private final static String LOCAL_DUCUMENT_NAME = "vipshop";

	public static final class SUFFIX
	{
		public static final String JPG = ".jpg";

		public static final String PNG = ".png";
	}
	/***
	 * ��洢���ļ�
	 * @return
	 * @throws FileNotFoundException
	 */
	public static File getSDCardFile(String filename)
	{
		String path = new File(Environment.getExternalStorageDirectory(),LOCAL_DUCUMENT_NAME).getPath()+"/"+filename;
		File file = new File(path);
		if(U.isSDCardAvaiable()){
			return file;
		}else{
			return null;
		}

	}

	public static File getDataFile(Context mContext,String filename){
		File file = new File(mContext.getFilesDir().getPath());
		if(file.isDirectory()){
			File[] fs = file.listFiles();
			for(File f : fs){
				if(f.getName().equals(filename)){
//					MyLog.error(mContext.getClass(),"找到:"+f.getName());
					return f;
				}
			}
		}
		return null;
	}

	public static boolean isExists(String filename)
	{
		if(U.isSDCardAvaiable()){
			String path = new File(Environment.getExternalStorageDirectory(),LOCAL_DUCUMENT_NAME).getPath()+"/"+filename;
			File file = new File(path);
			if( ! file.exists() || file.isDirectory() || file.length()== 0 ){
				return false;
			}else{
				return true;
			}
		}else{
			return false;
		}
	}
	/***
	 * �����ļ���
	 * @param is
	 * @param os
	 * @return
	 * @throws IOException
	 */
	public static boolean saveFile(InputStream is,OutputStream os) throws IOException
	{
        	byte[] data = new byte[is.available()];
			is.read(data);
	        os.write(data);
	        is.close();
	        os.close();
	        return true;
	}
	/***
	 * ��ȡ�ļ���
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static byte[] openFile(InputStream is) throws IOException
	{
			int size=is.available(); //��ȡ��ĳ���
			byte[] buffer=new byte[size];     //������ȵ��ֽ�����
			is.read(buffer);    //�����е����ݷŵ�buffer������
			is.close();
			return buffer;
	}





	public static byte[] openFile(Context context,String filename) throws IOException
	{
		FileInputStream is = context.openFileInput(filename);
		return openFile(is);
	}


	public static boolean saveFile(Context context,String filename,InputStream is) throws IOException
	{
		FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
		return saveFile(is,fos);
	}



	/***
	 * ��ȡ��洢����ļ�
	 * @param dirname
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static byte[] openFile(String filename) throws IOException
	{
			File file = getSDCardFile(filename);
			FileInputStream is = new FileInputStream(file);
			return openFile(is);
	}
	/***
	 * �����ļ�����洢��
	 * @param dirname
	 * @param filename
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static boolean saveFile(String filename,InputStream is) throws IOException
	{
			File file = getSDCardFile(filename);
			FileOutputStream os = new FileOutputStream(file);
			return saveFile(is, os);
	}

	/**
	 * ɾ����洢����ļ�
	 * @param filename
	 * @return
	 *
	 */
	public static boolean removeFile(String filename)
	{
		File file = getSDCardFile(filename);
		if(file != null ){
			return file.delete();
		}else{
			return false;
		}
	}

	public static void removeFiles(String dir,FileFilter filter){
		File file = getSDCardFile(dir);
		if(file != null){
			File[] files = file.listFiles(filter);
			if(files!=null && files.length != 0){
				for(File f:files){
					removeDir(f);
				}
			}
		}
	}

	public static void removeDir(File file){
		if(file.isDirectory()){
			File[] fs = file.listFiles();
			for(File f : fs){
				if(f.exists())
					removeDir(f);
			}
		}

	}

	public static String getSuffix(String filename)
	{
		try {
			int beginIndex = filename.lastIndexOf(".");
			String result = filename.substring(beginIndex).trim();
			int length = result.length();
			if(length > 0 && length < 5){
				return result;
			}else{
				return "";
			}
		} catch (Exception e) {
			return "";
		}
	}


	/**
	 * 写文本文件
	 * 在Android系统中，文件保存在 /data/data/PACKAGE_NAME/files 目录下
	 * @param context
	 * @param msg
	 */
	public static void write(Context context, String fileName, String content)
	{
		if( content == null )	content = "";

		try
		{
			FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
			fos.write( content.getBytes() );

			fos.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 读取文本文件
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static String read( Context context, String fileName )
	{
		try
		{
			FileInputStream in = context.openFileInput(fileName);
			return readInStream(in);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return "";
	}

	private static String readInStream(FileInputStream inStream)
	{
		try
		{
		   ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		   byte[] buffer = new byte[512];
		   int length = -1;
		   while((length = inStream.read(buffer)) != -1 )
		   {
			   outStream.write(buffer, 0, length);
		   }

		   outStream.close();
		   inStream.close();
		   return outStream.toString();
		}
		catch (IOException e)
		{
		   Log.i("FileTest", e.getMessage());
		}
		return null;
	}

	public static File createFile( String folderPath, String fileName )
	{
		File destDir = new File(folderPath);
		if (!destDir.exists())
		{
			destDir.mkdirs();
		}
		return new File(folderPath,  fileName + fileName );
	}

	/**
	 * 向手机写图片
	 * @param buffer
	 * @param folder
	 * @param fileName
	 * @return
	 */
	public static boolean writeFile( byte[] buffer, String folder, String fileName )
	{
		boolean writeSucc = false;

		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

		String folderPath = "";
		if( sdCardExist )
		{
			folderPath = Environment.getExternalStorageDirectory() + File.separator +  folder + File.separator;
		}
		else
		{
			writeSucc =false;
		}

		File fileDir = new File(folderPath);
		if(!fileDir.exists())
		{
			fileDir.mkdirs();
		}

		File file = new File( folderPath + fileName );
		FileOutputStream out = null;
		try
		{
			out = new FileOutputStream( file );
			out.write(buffer);
			writeSucc = true;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {out.close();} catch (IOException e) {e.printStackTrace();}
		}

		return writeSucc;
	}

	/**
	 * 根据文件绝对路径获取文件名
	 * @param filePath
	 * @return
	 */
	public static String getFileName( String filePath )
	{
		if( StringHelper.isBlank(filePath) )	return "";
		return filePath.substring( filePath.lastIndexOf( File.separator )+1 );
	}

	/**
	 * 根据文件的绝对路径获取文件名但不包含扩展名
	 * @param filePath
	 * @return
	 */
	public static String getFileNameNoFormat( String filePath){
		if(StringHelper.isBlank(filePath)){
			return "";
		}
		int point = filePath.lastIndexOf('.');
		return filePath.substring(filePath.lastIndexOf(File.separator)+1,point);
	}

	public static byte[] resBitmap(Bitmap bm){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	/**
	 * 获取文件扩展名
	 * @param fileName
	 * @return
	 */
	public static String getFileFormat( String fileName )
	{
		if( StringHelper.isBlank(fileName) )	return "";

		int point = fileName.lastIndexOf( '.' );
		return fileName.substring( point+1 );
	}

	/**
	 * 获取文件大小
	 * @param filePath
	 * @return
	 */
	public static long getFileSize( String filePath )
	{
		long size = 0;

		File file = new File( filePath );
		if(file!=null && file.exists())
		{
			size = file.length();
		}
		return size;
	}

	/**
	 * 获取文件大小
	 * @param size 字节
	 * @return
	 */
	public static String getFileSize(long size)
	{
		if (size <= 0)	return "0";
		java.text.DecimalFormat df = new java.text.DecimalFormat("##.##");
		float temp = (float)size / 1024;
		if (temp >= 1024)
		{
			return df.format(temp / 1024) + "M";
		}
		else
		{
			return df.format(temp) + "K";
		}
	}

	public static byte[] toBytes(InputStream in) throws IOException
	{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
	    int ch;
	    while ((ch = in.read()) != -1)
	    {
	    	out.write(ch);
	    }
	    byte buffer[]=out.toByteArray();
	    out.close();
	    return buffer;
	}


}
